package com.xyy.saas.payment.callback.core.handler;

import com.alibaba.fastjson.JSON;
import com.xyy.saas.payment.adpater.wechat.domain.EntrustDO;
import com.xyy.saas.payment.callback.core.result.CallbackRunner;
import com.xyy.saas.payment.common.Constants;
import com.xyy.saas.payment.dao.model.EntrustPayInfo;
import com.xyy.saas.payment.service.EntrustPayInfoService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 微信委托成功处理器
 */
@Component
public class WxEntrustSuccessHandler implements BaseHandler {

    private static final Logger LOGGER = LoggerFactory.getLogger(WxEntrustSuccessHandler.class);

    @Autowired
    private CallbackRunner callbackRunner;

    @Autowired
    private EntrustPayInfoService entrustPayInfoService;

    @Override
    public String getMethod() {
        return Constants.METHOD_WXENTRUST_SUCCESS_NAME;
    }

    @Override
    public boolean callBackHandler(Object domain) {
        EntrustDO entrustDO = (EntrustDO)domain;
        if (domain==null){
            LOGGER.error("WxEntrustSuccessHandler callBackHandler wxentrust callback fail domain is null");
            return false;
        }
        //校验通讯标识
        if (!"SUCCESS".equals(entrustDO.getReturnCode())) {
            LOGGER.error("WxEntrustSuccessHandler callBackHandler error ReturnCode is FAIL entrustDO:{}", JSON.toJSON(entrustDO));
            return false;
        }
        //校验是否成功
        if (!"SUCCESS".equals(entrustDO.getResultCode())) {
            LOGGER.error("WxEntrustSuccessHandler callBackHandler error ResultCode is FAIL entrustDO:{}", JSON.toJSON(entrustDO));
            return true;
        }
        // 查询签约单
        EntrustPayInfo entrustPayInfo = entrustPayInfoService.selectByContractCode(entrustDO.getContractCode());
        if (entrustPayInfo==null){
            LOGGER.error("WxEntrustSuccessHandler callBackHandler entrustPayInfo is null entrustPayInfo:{}, entrustDO:{}", JSON.toJSON(entrustPayInfo), JSON.toJSON(entrustDO));
            return false;
        }

        entrustDO.setCount(0);
        callbackRunner.wxEntrustCallback(entrustDO);
        return true;
    }
}
